import { CSSProperties, memo, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, Empty, Image, Input, Pagination, Spin } from 'antd';
import { API_BASEURL } from '@/constants/api';
import { resMyGoods, resUsersGoods } from '@/services/goods';
import { usePagination } from 'ahooks';

const GoodsItems: FC<PropsWithChildren<{ data: API.GoodsStruct }>> = ({
  data,
}) => {
  const navigate = useNavigate();
  return (
    <Card
      size={'small'}
      onClick={() => {
        navigate(`/goods_detail/` + data.id);
      }}
      hoverable
      cover={
        <Image
          className={'p-1'}
          preview={false}
          alt={''}
          width={145.6}
          src={API_BASEURL + '/' + data.cover}
        />
      }
    >
      <Card.Meta title={data.title} description={<div className={"truncate-2"} >{data.description}</div>} />
    </Card>
  );
};

export const paginationStyle: CSSProperties = { marginTop: 16, textAlign: 'right' };

const GoodsList: FC<PropsWithChildren<{ id: number }>> = ({ id }) => {
  const [title, setTitle] = useState('');
  const { data, loading, pagination, run, params } = usePagination(
    ({ current, pageSize }) => {
      return resUsersGoods(id, {
        current,
        pageSize,
        title: title,
      });
    },
    {
      cacheKey: 'goodsList',
      refreshDeps: [title],
    }
  );

  const searchBar = (
    <div className={'flex-justify-items-center'}>
      <div className={'w-[50%]'}>
        <Input.Search
          placeholder={'请输入图书名称关键字进行搜索'}
          onSearch={(value) => {
            setTitle(value);
          }}
        />
      </div>
    </div>
  );

  return (
    <div>
      {searchBar}
      <Spin spinning={loading}>
        <div
          className={
            'grid grid-cols-5 place-content-center place-items-start gap-6 py-6 '
          }
        >
          {data &&
            data.total > 0 &&
            data.list.map((value) => (
              <GoodsItems key={value.id} data={value} />
            ))}
          {!loading && data?.total === 0 && <Empty />}
        </div>
      </Spin>
      <Pagination
        current={pagination.current}
        pageSize={pagination.pageSize}
        total={data?.total}
        onChange={pagination.onChange}
        onShowSizeChange={pagination.onChange}
        showQuickJumper
        showSizeChanger
        style={paginationStyle}
      />
    </div>
  );
};

export default memo(GoodsList);
